//
//  SRMyHandRingViewController.m
//  SportRing
//
//  Created by icelee on 14-11-1.
//  Copyright (c) 2014年 HotOne. All rights reserved.
//

#import "SRMyHandRingViewController.h"
#import "SRMe+Cate.h"
#import "SRDevice+Cate.h"
#import "SRManager.h"

@interface SRMyHandRingViewController ()<SRHandRingViewDelegate>

@property (nonatomic, weak)IBOutlet SRHandRingView *srHandRingView;

@end

@implementation SRMyHandRingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addBackButton];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didFindPeripheral)
                                                 name:@"didFindPeripheral"
                                               object:nil];
}

-(void)didFindPeripheral
{
    [self setupData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self hideTabbar];
    [self setupData];
    self.navigationController.navigationBarHidden = NO;
}

- (void)setupData
{
    NSMutableArray *boundedHandRingArray = [NSMutableArray new];
    __block NSMutableArray *canUseHandRingArray = [NSMutableArray new];

    SRMe * me = [SRMe currentUser];
    SRDevice * device = me.device;
    if (device) {
        NSString * name = device.name;
        [boundedHandRingArray addObject:name];
        _srHandRingView.boundedHandRingArray = boundedHandRingArray;
    } else
    {
        _srHandRingView.boundedHandRingArray = [@[] mutableCopy];
    }

    NSArray * devices = [SRManager sharedInstance].findDevices;
    [devices enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        CBPeripheral * per = obj;
        SRMe * me = [SRMe currentUser];
        SRDevice * device = me.device;
        if (device != nil && [per.name isEqualToString:device.name]) {
            // pass
        }
        else
        {
            [canUseHandRingArray addObject:per.name];
        }
    }];
    _srHandRingView.canUseHandRingArray = canUseHandRingArray;
}

#pragma mark - SRHandRingViewDelegate

- (void)removeHandRing:(NSString *)ringID
{
    [[SRManager sharedInstance] disconnectWithDevice];
    SRDevice * device = [SRDevice findDeviceForMe:[SRMe currentUser]];
    [SRDevice deleteDevice:device];
    [self setupData];
}

- (void)boundHandRing:(NSString *)ringID
{
    SRDevice * device = [SRDevice findDeviceForMe:[SRMe currentUser]];
    [SRDevice deleteDevice:device];
    device = [SRDevice findDeviceCINEForMe:[SRMe currentUser]];
    [device configAttributesWithBlock:^(SRDevice *deviceSelf) {
        deviceSelf.name = ringID;
    }];
    [[SRManager sharedInstance] setCurrentPeripheralName:ringID];
    [self setupData];
}

@end
